<template>
    <base-breadcrumb :breadcrumb="!isAudit">
        <a-card>
            <titleName title="基本信息"></titleName>
            <a-form-model
                ref="ruleForm"
                :model="form"
                :rules="rules"
                :labelCol="{ lg: { span: 6 }, sm: { span: 6 } }"
                :wrapperCol="{ lg: { span: 16 }, sm: { span: 16 } }"
            >
                <a-row :gutter="24">
                    <a-col :md="16" :sm="16">
                    <a-form-model-item label="所属单位" prop="project" :labelCol="{ lg: { span: 6 }, sm: { span: 6 } }" :wrapperCol="{ lg: { span: 16 }, sm: { span: 16 } }">
                        <org-tree-select v-model="form.projectId" :disabled="pageType == 'look'"  isAutoSelectFirst checkStrictly @select="selectOrg"></org-tree-select>
                    </a-form-model-item>
                    </a-col>
                    <!-- <a-col :md="8" :sm="8">
                        <a-form-model-item label="所属分公司" prop="branchComId">
                            <SelectSubCompany
                                placeholder="请选择"
                                v-model="form.branchComId"
                                :disabled="pageType == 'look'"
                            ></SelectSubCompany>
                        </a-form-model-item>
                    </a-col>
                    <a-col :md="8" :sm="8">
                        <a-form-model-item label="所属项目" prop="projectId">
                            <SelectProject
                                placeholder="请选择"
                                v-model="form.projectId"
                                :form="form"
                                :isClear="id == ''"
                                keyValue="branchComId"
                                @change="handleChange"
                                :disabled="pageType == 'look'"
                            ></SelectProject>
                        </a-form-model-item>
                    </a-col> -->
                    <a-col :md="8" :sm="8">
                        <a-form-model-item label="项目编号">
                            <BaseInput disabled placeholder="请输入" v-model="form.projectNum" />
                        </a-form-model-item>
                    </a-col>
                    <a-col :md="8" :sm="8">
                        <a-form-model-item label="合同生效时间" prop="contractEffectiveTime">
                            <a-date-picker
                                :disabled="pageType == 'look'"
                                @change="
                                    (date, dateString) => getTime(date, dateString, 'form', 'contractEffectiveTime')
                                "
                                v-model="form.contractEffectiveTime"
                            />
                        </a-form-model-item>
                    </a-col>
                    <a-col :md="8" :sm="8">
                        <a-form-model-item label="合同金额(万元)">
                            <BaseInput disabled placeholder="请输入" v-model="form.contractValue" />
                        </a-form-model-item>
                    </a-col>
                    <a-col :md="8" :sm="8">
                        <a-form-model-item label="业主全称">
                            <BaseInput disabled placeholder="请输入" v-model="form.constructionName" />
                        </a-form-model-item>
                    </a-col>
                    <a-col :md="8" :sm="8">
                        <a-form-model-item label="业主性质">
                            <BaseInput disabled placeholder="请输入" v-model="form.constructionNatureName" />
                        </a-form-model-item>
                    </a-col>
                    <a-col :md="8" :sm="8">
                        <a-form-model-item label="业主隶属集团公司全称" prop="groupCompany">
                            <BaseInput
                                :disabled="pageType == 'look'"
                                placeholder="请输入"
                                v-model="form.groupCompany"
                            />
                        </a-form-model-item>
                    </a-col>
                    <a-col :md="8" :sm="8">
                        <a-form-model-item label="合同开工日期">
                            <BaseInput disabled placeholder="请输入" v-model="form.contractStartDate" />
                        </a-form-model-item>
                    </a-col>
                    <a-col :md="8" :sm="8">
                        <a-form-model-item label="实际开工日期">
                            <BaseInput disabled placeholder="请输入" v-model="form.startWorkingTime" />
                        </a-form-model-item>
                    </a-col>
                    <a-col :md="8" :sm="8">
                        <a-form-model-item label="合同竣工日期">
                            <BaseInput disabled placeholder="请输入" v-model="form.contractEndDate" />
                        </a-form-model-item>
                    </a-col>
                    <a-col :md="8" :sm="8">
                        <a-form-model-item label="项目状态">
                            <BaseInput disabled placeholder="请输入" v-model="form.statusName" />
                        </a-form-model-item>
                    </a-col>
                    <a-col :md="8" :sm="8">
                        <a-form-model-item label="履约保证金形式" prop="performanceBondForm">
                            <a-select
                                placeholder="请选择"
                                v-model="form.performanceBondForm"
                                :disabled="pageType == 'look'"
                            >
                                <a-select-option v-for="item in SelectList8" :key="item.id" :value="item.id">{{
                                    item.name
                                }}</a-select-option>
                            </a-select>
                        </a-form-model-item>
                    </a-col>
                    <a-col :md="8" :sm="8">
                        <a-form-model-item label="履约保证金比例(%)" prop="performanceBondRatio">
                            <BaseInputNumber
                                :min="0"
                                :max="100"
                                :disabled="pageType == 'look'"
                                placeholder="请输入"
                                v-model="form.performanceBondRatio"
                            />
                        </a-form-model-item>
                    </a-col>
                    <a-col :md="8" :sm="8">
                        <a-form-model-item label="履约保证金返还时间" prop="performanceBondReturnTime">
                            <a-date-picker
                                :disabled="pageType == 'look'"
                                @change="
                                    (date, dateString) => getTime(date, dateString, 'form', 'performanceBondReturnTime')
                                "
                                v-model="form.performanceBondReturnTime"
                            />
                        </a-form-model-item>
                    </a-col>
                    <a-col :md="8" :sm="8">
                        <a-form-model-item label="有无预付款" prop="prepayment">
                            <a-select :disabled="pageType == 'look'" placeholder="请选择" v-model="form.prepayment">
                                <a-select-option :value="1">有</a-select-option>
                                <a-select-option :value="0">无</a-select-option>
                            </a-select>
                        </a-form-model-item>
                    </a-col>

                    <a-col :md="8" :sm="8">
                        <a-form-model-item label="付款条件" prop="payCondition">
                            <a-select placeholder="请选择" v-model="form.payCondition" :disabled="pageType == 'look'">
                                <a-select-option v-for="item in SelectList6" :key="item.id" :value="item.id">{{
                                    item.name
                                }}</a-select-option>
                            </a-select>
                        </a-form-model-item>
                    </a-col>
                    <a-col :md="8" :sm="8">
                        <a-form-model-item label="结算条件" prop="settlementCondition">
                            <a-select
                                placeholder="请选择"
                                v-model="form.settlementCondition"
                                :disabled="pageType == 'look'"
                            >
                                <a-select-option v-for="item in SelectList7" :key="item.id" :value="item.id">{{
                                    item.name
                                }}</a-select-option>
                            </a-select>
                        </a-form-model-item>
                    </a-col>
                    <a-col :md="8" :sm="8">
                        <a-form-model-item label="付款比例(%)" prop="paymentRatio">
                            <BaseInputNumber
                                :min="0"
                                :max="100"
                                :disabled="pageType == 'look'"
                                placeholder="请输入"
                                v-model="form.paymentRatio"
                            />
                        </a-form-model-item>
                    </a-col>
                    <a-col :md="8" :sm="8">
                        <a-form-model-item label="质量保证金比例(%)" prop="qualityMarProportion">
                            <BaseInputNumber
                                :min="0"
                                :max="100"
                                :disabled="pageType == 'look'"
                                placeholder="请输入"
                                v-model="form.qualityMarProportion"
                            />
                        </a-form-model-item>
                    </a-col>

                    <a-col :md="8" :sm="8">
                        <a-form-model-item label="质量保证金返还时间" prop="qualityMarReturnTime">
                            <a-date-picker
                                :disabled="pageType == 'look'"
                                @change="
                                    (date, dateString) => getTime(date, dateString, 'form', 'qualityMarReturnTime')
                                "
                                v-model="form.qualityMarReturnTime"
                            />
                        </a-form-model-item>
                    </a-col>
                    <a-col :md="8" :sm="8">
                        <a-form-model-item label="担保或承诺事项" prop="guaranteeOrPromise">
                            <BaseInput
                                :disabled="pageType == 'look'"
                                placeholder="请输入"
                                v-model="form.guaranteeOrPromise"
                            />
                        </a-form-model-item>
                    </a-col>
                    <a-col :md="8" :sm="8">
                        <a-form-model-item label="项目预计上缴利润率(%)" prop="projectExpHandInProMargin">
                            <BaseInputNumber
                                :min="0"
                                :max="100"
                                :disabled="pageType == 'look'"
                                placeholder="请输入"
                                v-model="form.projectExpHandInProMargin"
                            />
                        </a-form-model-item>
                    </a-col>
                    <a-col :md="8" :sm="8">
                        <a-form-model-item label="预计变更后毛利率(%)" prop="expectedAftChangeGroMargin">
                            <BaseInputNumber
                                :disabled="pageType == 'look'"
                                placeholder="请输入"
                                v-model="form.expectedAftChangeGroMargin"
                            />
                        </a-form-model-item>
                    </a-col>
                    <a-col :md="24" :sm="24" class="title">收入</a-col>
                    <a-col :md="8" :sm="8">
                        <a-form-model-item label="合同预计总收入(元)" prop="estimatedTotalConRevenue">
                            <BaseInputNumber
                                :min="0"
                                :max="99999999999"
                                :disabled="pageType == 'look'"
                                placeholder="请输入"
                                v-model="form.estimatedTotalConRevenue"
                            />
                        </a-form-model-item>
                    </a-col>
                    <a-col :md="8" :sm="8">
                        <a-form-model-item label="其中：初始合同预计总收入(元)" prop="estimatedTotalConRevenueInit">
                            <span class="flex">
                                <BaseInputNumber
                                    :min="0"
                                    :max="99999999999"
                                    :disabled="pageType == 'look'"
                                    placeholder="请输入"
                                    v-model="form.estimatedTotalConRevenueInit"
                                ></BaseInputNumber>
                                <a-button :disabled="pageType == 'look'" @click="addChange1" class="ml20" type="primary"
                                    >增加变更项</a-button
                                >
                            </span>
                        </a-form-model-item>
                    </a-col>
                    <a-col v-for="(item, index) in form.revenueEstimatedChanges" :key="index" :md="8" :sm="8">
                        <a-form-model-item :label="item.changeName">
                            <span class="flex">
                                <BaseInput
                                    :disabled="pageType == 'look'"
                                    placeholder="请输入"
                                    v-model="item.changeValue"
                                ></BaseInput>
                            </span>
                        </a-form-model-item>
                    </a-col>
                    <a-col :md="24" :sm="24" class="title">成本</a-col>
                    <a-col :md="8" :sm="8">
                        <a-form-model-item label="合同预计总成本(元)" prop="estimatedTotalContractCost">
                            <BaseInputNumber
                                :min="0"
                                :disabled="pageType == 'look'"
                                placeholder="请输入"
                                v-model="form.estimatedTotalContractCost"
                            />
                        </a-form-model-item>
                    </a-col>
                    <a-col :md="8" :sm="8">
                        <a-form-model-item label="其中：初始合同成本概算额(元)" prop="estimatedInitContractCost">
                            <span class="flex">
                                <BaseInputNumber
                                    :min="0"
                                    :disabled="pageType == 'look'"
                                    placeholder="请输入"
                                    v-model="form.estimatedInitContractCost"
                                ></BaseInputNumber>
                                <a-button :disabled="pageType == 'look'" @click="addChange2" class="ml20" type="primary"
                                    >增加变更项</a-button
                                >
                            </span>
                        </a-form-model-item>
                    </a-col>
                    <a-col
                        v-for="(item, index) in form.costEstimatedChanges"
                        :key="form.revenueEstimatedChanges.length + index"
                        :md="8"
                        :sm="8"
                    >
                        <a-form-model-item :label="item.changeName">
                            <span class="flex">
                                <BaseInput
                                    :disabled="pageType == 'look'"
                                    placeholder="请输入"
                                    v-model="item.changeValue"
                                ></BaseInput>
                            </span>
                        </a-form-model-item>
                    </a-col>

                    <a-col v-if="pageType != 'look'" :md="24" :sm="24">
                        <a-form-model-item label="附件上传">
                            <upload-list
                                :businessCode="'BM21'"
                                :uploadArrys.sync="form.fileInfoVOList"
                                @fileArrysData="handleFileUploaded"
                                multiple
                            ></upload-list>
                        </a-form-model-item>
                    </a-col>
                    <a-col :md="24" :sm="24" v-else>
                        <a-form-model-item label="附件">
                            <file-link :fileList="form.fileInfoVOList"></file-link>
                        </a-form-model-item>
                    </a-col>
                </a-row>
            </a-form-model>
        </a-card>

        <div class="tool-btns page-btn-right-top" v-if="pageType != 'look'">
            <a-button
                v-if="id != '' && form.auditStatus == 'DRAFT'"
                type="danger"
                :loading="loading.DELETE"
                @click="handleSave('DELETE')"
                >删除草稿</a-button
            >
            <a-button
                v-if="form.auditStatus == 'REJECTED'"
                type="primary"
                :loading="loading.REJECTED"
                @click="handleSave('REJECTED')"
                >保存</a-button
            >
            <a-button v-else type="primary" :disabled="!isSubmit" :loading="loading.DRAFT" @click="handleSave('DRAFT')"
                >保存草稿</a-button
            >
            <a-button type="primary"  :disabled="!isSubmit" :loading="loading.SUBMITTED" @click="handleSave('SUBMITTED')"
                >提交</a-button
            >
            <a-button type="primary" @click="handleClose">关闭</a-button>
        </div>
        <div class="tool-btns page-btn-right-top" v-else>
            <BasePrintButton
                type="primary"
                v-if="form.auditStatus == 'PAST'"
                :beforePrintFn="checkRevenueCostInputPrint"
            />
            <a-button type="primary" class="ml20" @click="handleClose" v-if="checkVisibleInDetail">关闭</a-button>
        </div>
       <selectApprover :businessId="businessId"  :processConfig="setProcessConfig"></selectApprover>
    </base-breadcrumb>
</template>
<script>
import { getProjectInfo } from '@/api/businessAffairs/revenueAndCost'
import {
    getRevenueCostInput,
    addRevenueCostInput,
    editRevenueCostInput,
    delRevenueCostInput,
    checkRevenueCostInput,
    checkRevenueCostInputPrint
} from '@/api/businessAffairs/expectRevenueAndCost'
import { getSelectListByType } from '@/api/businessAffairs/common.js'
import SelectSubCompany from '@/components/Select/SelectSubCompany' // 分公司
import SelectProject from '@/components/Select/SelectProject' // 分公司
import { isAttachment, checkVisibleInDetail } from '@/utils/util'
import { STable } from '@/components'
import UploadList from '@/components/UploadList'
import BasePrintButton from '@/components/BasePrintButton' // 打印按钮
export default {
    name: 'a' + Date.now(),
    components: {
        SelectSubCompany,
        SelectProject,
        STable,
        UploadList,
        BasePrintButton
    },
    data() {
        return {
            checkVisibleInDetail: checkVisibleInDetail(this),
            loading: {
                DELETE: false,
                DRAFT: false,
                SUBMITTED: false,
                REJECTED: false
            },
            form: {
                fileInfoVOList: [],
                costEstimatedChanges: [], //概算额
                revenueEstimatedChanges: [], //预计总收入
                projectNum: '',
                contractValue: '',
                contractStartDate: '',
                contractEndDate: '',
                constructionNatureName: '',
                constructionName: '',
                startWorkingTime: '',
                statusName: ''
            },

            rules: {
                branchComId: [{ required: true, message: '请选择分公司' }],
                projectId: [{ required: true, message: '请选择项目' }],
                contractEffectiveTime: [{ required: true, message: '请选择' }],
                performanceBondForm: [{ required: true, message: '请选择' }],
                performanceBondRatio: [{ required: true, message: '请输入' }],
                performanceBondReturnTime: [{ required: true, message: '请选择' }],
                prepayment: [{ required: true, message: '请选择' }],
                payCondition: [{ required: true, message: '请选择' }],
                settlementCondition: [{ required: true, message: '请选择' }],
                paymentRatio: [{ required: true, message: '请输入' }],
                qualityMarProportion: [{ required: true, message: '请输入' }],
                qualityMarReturnTime: [{ required: true, message: '请选择' }],
                guaranteeOrPromise: [{ required: true, message: '请输入' }],
                projectExpHandInProMargin: [{ required: true, message: '请输入' }],
                expectedAftChangeGroMargin: [{ required: true, message: '请输入' }],
                estimatedTotalConRevenue: [{ required: true, message: '请输入' }],
                estimatedTotalConRevenueInit: [{ required: true, message: '请输入' }],
                estimatedTotalContractCost: [{ required: true, message: '请输入' }],
                estimatedInitContractCost: [{ required: true, message: '请输入' }],
                groupCompany: [{ required: true, message: '请输入' }]
            },
            id: '',
            isSubmit: true,
            pageType: '',
            SelectList8: [], //履约保证金形式 8
            SelectList6: [], //付款条件 6
            SelectList7: [], //结算条件 7
           //获取流程配置值
            processConfig: null,
           //点击提交发送流程配置值
           setProcessConfig: null,
           businessId: null
        }
    },

   async mounted() {
        if (this.$route.query.id) {
            this.id = this.$route.query.id
            console.log(this.id)
            this.checkRevenueCostInputReq()
        }
        this.pageType = this.$route.query.pageType
        if (this.pageType == 'look') {
            this.$route.meta.title = '总收入与总成本录入查看'
        } else {
            this.$route.meta.title = this.id == '' ? '总收入与总成本录入新增' : '总收入与总成本录入编辑'
        }

        this.getSelectListByTypeReq(8)
        this.getSelectListByTypeReq(6)
        this.getSelectListByTypeReq(7)
       //获取通过获取流程配置值
       this.processConfig = await this.$getConfigFn('comm_expect_income_and_cost')
    },
    props: {
        isAudit: {
            // 是否作为审批详情
            type: Boolean,
            default: false
        }
    },
    watch: {
        isAudit: {
            immediate: true,
            handler(val) {
                if (val) {
                    this.$nextTick(() => {
                        this.pageType = 'look'
                    })
                }
            }
        }
    },

    methods: {
        //选择单位
        selectOrg(val) {
            if (val && val.length) {
                this.form.branchComId = val[val.length - 2].orgId;
                // this.form.projectName = val[val.length - 1].projectName
                // this.form.branchComName = val[val.length - 2].orgName
                this.handleChange(this.form.projectId)
            }
        },
        checkRevenueCostInputPrint() {
            return checkRevenueCostInputPrint({ id: this.id }).then((res) => {
                console.log(res)
                return res[1].data.content
            })
        },
        addChange1() {
            this.form.revenueEstimatedChanges.push({
                changeName: '变更' + (this.form.revenueEstimatedChanges.length + 1),
                changeValue: ''
            })
        },
        addChange2() {
            this.form.costEstimatedChanges.push({
                changeName: '变更' + (this.form.costEstimatedChanges.length + 1),
                changeValue: ''
            })
        },
        async getSelectListByTypeReq(type) {
            const [err, res] = await getSelectListByType({ type: type })
            if (!err) {
                switch (type) {
                    case 8:
                        this.SelectList8 = res.data
                        break
                    case 6:
                        this.SelectList6 = res.data
                        break
                    case 7:
                        this.SelectList7 = res.data
                        break

                    default:
                        break
                }
            }
        },
        handleFileUploaded(list) {
            this.form.fileInfoVOList = [...list]
        },
        getTime(date, dateString, type, name) {
            this[type][name] = dateString
            console.log(this[type][name])
        },

        //获取项目详情
        handleChange(e) {
            console.log(e)
            this.getProjectInfo(e)
            this.getIsProject(e)
        },
        //判断该项目是否可添加次业务
        async getIsProject(e) {
            const [err, res] = await getRevenueCostInput({ projectId: e, enter: true })
            if (res.data.length > 0 && this.id != res.data[0].id) {
                this.isSubmit = false
                this.$message.warning('总收入与总成本在该项目已存在，不可再次添加')
            } else {
                this.isSubmit = true
            }
        },
        getProjectInfo(id) {
            getProjectInfo({ projectId: id }).then((res) => {
                // this.$set(this.form, 'constructionArea', res.data.contractTotalArea)
                this.$set(this.form, 'projectNum', res.data.projectNum) //项目编号
                this.$set(this.form, 'contractValue', res.data.contractValue) //合同金额
                this.$set(this.form, 'contractStartDate', res.data.contractStartDate) //合同开工日期
                this.$set(this.form, 'contractEndDate', res.data.contractEndDate) //合同竣工日期
                this.$set(this.form, 'constructionName', res.data.constructionName) //业主全称
                this.$set(this.form, 'constructionNatureName', res.data.constructionNatureName) //业主性质
                this.$set(this.form, 'startWorkingTime', res.data.startWorkingTime) //实际开工日期
                this.$set(this.form, 'statusName', res.data.statusName) //项目状态
            })
        },

        async checkRevenueCostInputReq() {
            const [err, res] = await checkRevenueCostInput({ id: this.id })
            if (!err) {
                res.data.prepayment = res.data.prepayment ? 1 : 0
                this.form = res.data
                this.handleChange(this.form.projectId)
            }
        },
        validateForm() {
            let flag = false
            this.$refs.ruleForm.validate((valid) => {
              if(!valid) {
                this.$message.warning("请填写完所有必填项信息")
              }
                flag = valid
            })
            return flag
        },
        async delRevenueCostInput(params) {
            const [err, res] = await delRevenueCostInput(params)
            if (!err) {
                this.$message.success('成功')
                this.handleClose()
            }
        },
        // 处理增、删、改操作
        async handleSave(status) {
             this.setProcessConfig = null;
            if (this.loading[status]) return
            if (status !== 'DELETE') {
                if (!this.validateForm()) return

                if (isAttachment(this, status == 'SUBMITTED' ? 1 : 0, this.form.fileInfoVOList)) return
            }

            const params = {
                ...this.form,
                auditStatus: status,
                id: this.$route.query.id || void 0,
                prepayment: this.form.prepayment == 1
            }
            // console.log(params);
            // return;
            const { pageType } = this.$route.query
            const fn = pageType === 'edit' ? editRevenueCostInput : addRevenueCostInput
            const map = {
                DELETE: delRevenueCostInput,
                DRAFT: fn,
                SUBMITTED: fn,
                REJECTED: fn
            }

            if (status == 'DELETE') {
                let that = this
                this.$confirm({
                    title: '温馨提示',
                    content: '确定是否删除数据？',
                    okText: '确认',
                    okType: 'danger',
                    cancelText: '取消',
                    onOk: () => {
                        return that.delRevenueCostInput(params)
                    }
                })
              this.loading[status] = false
            } else {
                this.submitApprovalConfirm(status =='SUBMITTED'?this.processConfig:6, async (flag)=>{
                  if(!flag) {
                    this.loading[status] = false
                    return
                  }
                this.loading[status] = true
                const [err, res] = await map[status](params)
                if (!err) {
                    this.$message.success('成功')
                }
             if (status =='SUBMITTED') {
                //提交时，返回id
                    this.businessId = res.data.id || this.id;
                    this.setProcessConfig = this.processConfig;
                    return
                }else{
                  this.handleClose()
                }
                  this.loading[status] = false
                })
            }

        },
        handleClose() {
            if (this.isAudit) {
                window.close()
            } else {
                this.$multiTab.close(this.$route.fullpath)
            }
        }
    }
}
</script>
<style lang="less" scoped>
@deep: ~'>>>';
.tool-btns {
    display: flex;
    justify-content: flex-end;
    @{deep} .ant-btn + .ant-btn {
        margin-left: 12px;
    }
}
.flex {
    display: flex;
    flex-wrap: nowrap;
    align-items: center;
    height: 40px;
}
.title {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    text-align: left;
    font-weight: bold;
    margin-bottom: 24px;
}
</style>
